package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * TODO
 *
 * @Author mr.lin
 * @Date 2025/1/26 18:10
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 上传图片
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        //1.把图片上传到minio中
        try {
            //1.1获取图片的绝对名字
            String originalFilename = multipartFile.getOriginalFilename();
            //1.2获取后缀名,再用uuid生成随机文件名
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString().replace("-", "") + substring;
            String img_path = fileStorageService.uploadImgFile("", fileName, multipartFile.getInputStream());
            //2.封装数据插入到wm_material表中
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
            wmMaterial.setUrl(img_path);
            wmMaterial.setType((short) 0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setCreatedTime(new Date());
            save(wmMaterial);
            //3.返回响应结果
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 图片列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult imgList(WmMaterialDto dto) {
        //1.调用方法,对page,size判断
        dto.checkParam();

        //2.使用分页插件进行列表查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.lambdaQuery();
        if (dto.getIsCollection() != 0) {
            //添加收藏的条件
            queryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //添加用户id的查询条件
        queryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());
        IPage<WmMaterial> page1 = page(page, queryWrapper);
        ResponseResult responseResult = new PageResponseResult((int) page1.getCurrent(), (int) page1.getSize(), (int) page1.getTotal());
        responseResult.setData(page1.getRecords());
        return responseResult;
    }

    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteImg(Integer id) {
        //1.根据id去中间表wm_news_material查询是否有数据
        Integer count = wmNewsMaterialService.lambdaQuery().eq(WmNewsMaterial::getMaterialId, id)
                .count();
        if (count > 0) {
            //被引用了,不能删除
            return ResponseResult.errorResult(HttpStatus.BAD_REQUEST.value(), "该图片被引用,不能删除");
        }
        //2.没有数据,进行删除,并且需要在minio服务中也要删除掉
        WmMaterial material = getById(id);
        if (material == null) {
            return ResponseResult.errorResult(HttpStatus.BAD_REQUEST.value(), "没有该素材图片");
        }
        //minio服务删除
        fileStorageService.delete(material.getUrl());
        //数据库删除
        removeById(id);
        return ResponseResult.okResult(200, "操作成功");
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        //1.根据id查询wm_material表
        WmMaterial material = getById(id);
        if (material == null) {
            return ResponseResult.errorResult(HttpStatus.BAD_REQUEST.value(), "没有该素材图片");
        }
        //2.改为取消收藏
        boolean flag = lambdaUpdate().eq(WmMaterial::getId, id)
                .set(WmMaterial::getIsCollection, 0)
                .update();
        if (!flag) {
            return ResponseResult.errorResult(HttpStatus.BAD_REQUEST.value(), "修改失败");
        }
        return ResponseResult.okResult(200, "操作成功");
    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        //1.根据id查询wm_material表
        WmMaterial material = getById(id);
        if (material == null) {
            return ResponseResult.errorResult(HttpStatus.BAD_REQUEST.value(), "没有该素材图片");
        }
        //2.改为收藏
        boolean flag = lambdaUpdate().eq(WmMaterial::getId, id)
                .set(WmMaterial::getIsCollection, 1)
                .update();
        if (!flag) {
            return ResponseResult.errorResult(HttpStatus.BAD_REQUEST.value(), "修改失败");
        }
        return ResponseResult.okResult(200, "操作成功");
    }
}
